package com.yuan.support;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    public static final int REQUEST_CODE_PICK_PIC = 100; // 选择照片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
            }
        }

        DocumentFileUtils.checkSDCardPermission(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: ");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: requestCode=" + requestCode + " resultCode=" + resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_PICK_PIC) { // 选择照片
                // handlePic(data.getData());

                handlePic(data);
            }
        }
    }

    private void handlePic(final Intent intent) {
        String filePath = PictureFileUtils.getFilePathFromIntent(intent);
        if (TextUtils.isEmpty(filePath)) {
            return;
        }

        File imageFile = new File(filePath);

        // File file = new KtUtils().other(imageFile);

        try {
            Log.d(TAG, "NativeUtil.compressBitmap: start");
            NativeUtil.compressBitmap(imageFile.getAbsolutePath(), imageFile.getAbsolutePath());
            Log.d(TAG, "NativeUtil.compressBitmap: end");
            Toast.makeText(getApplicationContext(), "NativeUtil.compressBitmap "
                    + FileUtils.getFileSize(imageFile.length()), Toast.LENGTH_SHORT).show();
            FileUtils.scanFile(filePath, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlePic(final Uri uri) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Looper.prepare();

                    // 从Intent的uri数据中解析出path
                    String[] proj = {MediaStore.Images.Media.DATA};
                    // todo 特殊情况三 M2报错：Can't create handler inside thread that has not called Looper.prepare()
                    Cursor cursor = new CursorLoader(getApplicationContext(), uri, proj, null, null, null).loadInBackground();
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    String path = cursor.getString(columnIndex);
                    cursor.close();

                    File file = new File(path);
                    boolean canRead = file.canRead();
                    boolean canWrite = file.canWrite();
                    Log.d(TAG, "path: " + path + "\n" +
                            "canRead=" + canRead + " canWrite=" + canWrite);

                    Bitmap bitmap = BitmapFactory.decodeFile(path); // 可读即可解码
                    Log.d(TAG, "可读即可解码: " + bitmap);

                    String string = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

                    Bitmap bitmap2 = createWaterMark(bitmap, "水印：" + string);

                    new File(path).deleteOnExit();

                    compressAndGenImage(bitmap2, path, 300);

                    Log.d(TAG, "ok " + new File(path).exists());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            }
        }).start();
    }

    private void initView() {
        findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ");

                // 调用系统的照片选择界面
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE_PICK_PIC);
            }
        });
    }

    private Bitmap createWaterMark(Bitmap bitmap, String mark) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        TextPaint p = new TextPaint();
        p.setColor(Color.RED);
        p.setTextSize(40);
        p.setAntiAlias(true);
        canvas.drawBitmap(bitmap, 0, 0, p);
        StaticLayout sl = new StaticLayout(mark, p, w - 60, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        canvas.translate(50, 50);
        sl.draw(canvas);
        return bmp;
    }

    private void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int options = 100;//比例
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
        while (os.toByteArray().length / 1024 > maxSize) {
            os.reset();
            options -= 2;
            image.compress(Bitmap.CompressFormat.JPEG, options, os);
        }

        // FileOutputStream fos = new FileOutputStream(outPath);
        // fos.write(os.toByteArray());
        // fos.flush();
        // fos.close();

        OutputStream outputStream = DocumentFileUtils.getOutputStream(outPath);
        Log.d(TAG, "compressAndGenImage: outputStream=" + outputStream);
        outputStream.write(os.toByteArray());
        outputStream.flush();
        outputStream.close();
    }
}